<template>
  <el-dialog
    title="选择城市"
    :visible.sync="open"
    :close-on-click-modal="false"
    append-to-body
    width="900px"
    destroy-on-close
  >
    <el-row>
      <el-col v-for="(city, index) in list" :key="city.cityId" :span="6" class="mb20">
        <el-popover placement="bottom" width="200" trigger="hover">
          <div style="max-height: 200px;overflow:auto;padding:10px">
            <el-row v-for="(child, i) in city.children" :key="child.cityId">
              <el-col :span="24" :class="{ 'mb10': i < city.children.length - 1 }">
                <el-checkbox
                  v-model="child.checked"
                  :label="child.cityId"
                  @change="val => onCityChildChange(val, index)"
                >
                  {{ child.name }}
                </el-checkbox>
              </el-col>
            </el-row>
          </div>
          <el-checkbox
            slot="reference"
            v-model="city.checked"
            :label="city.cityId"
            :indeterminate="isIndeterminate(index)"
            @change="val => onCityChange(val, index)"
          >
            {{ city.name }}
            <span style="color:#ff0000;margin-left: 1px;">
              ({{ getSelectCount(index) }}/{{ city.children.length }})
            </span>
          </el-checkbox>
        </el-popover>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onOK">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { listCities } from '@/api/templates/templates'
export default {
  name: 'CitySelector',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [],
      open: false,
      rowCount: 0
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.listCities()
        } else {
          this.list = []
        }
        this.open = val
      },
      immediate: true
    }
  },
  methods: {
    isIndeterminate(index) {
      const selectCount = this.getSelectCount(index)
      return selectCount > 0 && selectCount !== this.list[index].children.length
    },
    getSelectCount(index) {
      let count = 0
      this.list[index].children.map(el => {
        if (el.checked) {
          count++
        }
      })
      return count
    },
    listCities() {
      listCities().then(({ data }) => {
        this.list = data
        for (let i = 0; i < this.list.length; i++) {
          const item = this.list[i]
          this.$set(this.list[i], 'checked', false)
          if (item.children) {
            for (let j = 0; j < item.children.length; j++) {
              this.$set(this.list[i].children[j], 'checked', false)
            }
          }
        }
        this.rowCount = Math.ceil(data.length / 4)
      })
    },
    getSelectedCities() {
      const result = JSON.parse(JSON.stringify(this.list))
      for (let i = result.length - 1; i > -1; i--) {
        let hasChildChecked = false
        const parent = result[i]
        if (!parent.checked) {
          const { children } = parent
          for (let j = children.length - 1; j > -1; j--) {
            const child = children[j]
            if (child.checked) {
              hasChildChecked = true
            } else {
              children.splice(j, 1)
            }
          }
        }
        if (!parent.checked && !hasChildChecked) {
          result.splice(i, 1)
        }
      }
      return result
    },
    onOK() {
      const result = this.getSelectedCities()
      if (result.length === 0) {
        return this.$message.warning('至少选择一个省份或者城市')
      }
      this.$emit('update:visible', false)
      this.$emit('save', result)
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    onCityChange(val, index) {
      this.list[index].children.map(_ => { _.checked = val })
    },
    onCityChildChange(val, index) {
      if (val) {
        if (this.getSelectCount(index) === this.list[index].children.length) {
          this.list[index].checked = true
        }
      } else {
        this.list[index].checked = false
      }
    }
  }
}
</script>
